package com.zzq.util;

import com.aliyun.oss.ClientException;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.logging.Logger;

/**
 * description: 短信工具
 */
@Component
public class SMSUtils {

	@Value("${aliyun.accessKeyId}")
	private String accessKeyId;
	@Value("${aliyun.accessKeySecret}")
	private String secret;
	@Value("${aliyun.msg.signName}")
	private String signName; // 短信签名
	@Value("${aliyun.msg.templateCode}")
	private String templateCode;  //短信模板
	@Value("${aliyun.msg.regionId}")
	private String regionId;   // 短信服务器区域


	public void sendMsg(String phone, String code) {

		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, secret);
		DefaultAcsClient client = new DefaultAcsClient(profile);
		CommonRequest request = new CommonRequest();

		request.setSysMethod(MethodType.POST);
		//下面两个不能动
		request.setSysProduct("Dysmsapi");
		request.setSysDomain("dysmsapi.aliyuncs.com");
		
		request.setSysVersion("2017-05-25");
		request.setSysAction("SendSms");
		//自定义参数(手机号,验证码,签名,模板)
		request.putQueryParameter("RegoinId", regionId);
		request.putQueryParameter("PhoneNumbers", phone);
		request.putQueryParameter("SignName", signName); //填自己申请的名称
		request.putQueryParameter("TemplateCode", templateCode);
		request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");

		try {
			CommonResponse response = client.getCommonResponse(request);
			System.out.println("阿里云短信响应信息：" + response.getData());
			boolean success = response.getHttpResponse().isSuccess();
			System.out.println("短信发送是否成功：" + success);
		} catch (ClientException e) {
			e.printStackTrace();
		} catch (ServerException e) {
            throw new RuntimeException(e);
        } catch (com.aliyuncs.exceptions.ClientException e) {
            throw new RuntimeException(e);
        }
    }
}
